//
//  SugAndComSearchVC.m
//  运营管理系统
//
//  Created by 杨毅 on 17/2/23.
//  Copyright © 2017年 杨毅. All rights reserved.
//

#import "SugAndComSearchVC.h"

@interface SugAndComSearchVC ()
{
    NSInteger userID;
    NSInteger ChooseTimeBtnTag;
    NSInteger sugesTypeId;
    NSInteger branchId;
    NSInteger pageNumber;

    NSString *_upImage;
    NSString *_WhetherName;//是否匿名
    NSDictionary *_infoDic;//通知带过来的参数
    
    UnusualBaseView *_UnusualBsView;
}
@property (nonatomic,strong)NSMutableArray *typeNameArray;
@property (nonatomic,strong)NSMutableArray *typeIDArray;
@property (nonatomic,strong)NSMutableArray *FGS_arry;//所有分公司
@property (nonatomic,strong)NSMutableArray *FGSid_arry;//所有分公司id;
@property (nonatomic,strong)UITableView *tableview;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)SearchHeardView *heardView;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation SugAndComSearchVC
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (NSString *)filePath{
    NSString *documentFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filetPath = [documentFilePath stringByAppendingPathComponent:@"Log.txt"];
    return filetPath;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"检索";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    //设置默认搜索 问题ID 分公司id
    sugesTypeId = -1;
    branchId = -1;
    
    _typeNameArray = [[NSMutableArray alloc]init];
    _typeIDArray = [[NSMutableArray alloc]init];
    _dataSource = [[NSMutableArray alloc]init];
    _FGS_arry = [[NSMutableArray alloc]init];
    _FGSid_arry = [[NSMutableArray alloc]init];
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    self.tableview.rowHeight = 180;
    _tableview.backgroundColor = UIColorFromRGB(0xf0f0f0);
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    //去掉多余的cell
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableview setTableFooterView:v];
    self.heardView = [[SearchHeardView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 97)];
    self.heardView.backgroundColor = UIColorFromRGB(0xffffff);
    self.heardView.delegate = self;
    [self.tableview setTableHeaderView:self.heardView];
    [self.view addSubview:_tableview];
    [self.tableview registerNib:[UINib nibWithNibName:@"SuggesOrComplainCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    NSDictionary *userDic = [NSDictionary dictionaryWithContentsOfFile:[self filePath]];
    userID =[[userDic objectForKey:@"userid"]integerValue];
    
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataSource removeAllObjects];
        pageNumber = 0;
        NSDictionary *prameter = @{@"pageNum":[NSString stringWithFormat:@"%ld",pageNumber],@"sortType":@0,@"userId":[NSString stringWithFormat:@"%ld",userID],@"startTime":self.heardView.startimeTF.text,@"endTime":self.heardView.endtimeTF.text,@"keyword":self.heardView.searchTF.text,@"suggestionType":[NSString stringWithFormat:@"%ld",sugesTypeId],@"branchId":[NSString stringWithFormat:@"%ld",branchId]};
        [self networking:prameter];
    }];
    self.tableview.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        pageNumber = pageNumber+1;
        NSDictionary *prameter = @{@"pageNum":[NSString stringWithFormat:@"%ld",pageNumber],@"sortType":@0,@"userId":[NSString stringWithFormat:@"%ld",userID],@"startTime":self.heardView.startimeTF.text,@"endTime":self.heardView.endtimeTF.text,@"keyword":self.heardView.searchTF.text,@"suggestionType":[NSString stringWithFormat:@"%ld",sugesTypeId],@"branchId":[NSString stringWithFormat:@"%ld",branchId]};
        [self networking:prameter];
    }];

    

}
- (void)sugBtnClick:(UIButton *)sender RowData:(NSDictionary *)rowDataDictionary{
    _infoDic = rowDataDictionary;
    
    //为了点赞成功还保持在原来的cell上 选用指定cell刷新 改变当前的原数据
    
    SugAndComBeanListModel *model = _dataSource[[_infoDic[@"row"]integerValue]];
    model.supportNum = [_infoDic[@"supprotNum"]integerValue];
    if ([_infoDic[@"type"] isEqualToString:@"cut"]) {
        model.supportState = [_infoDic[@"supprotState"]integerValue]-1;
        
    }else{
        model.supportState = [_infoDic[@"supprotState"]integerValue]+1;
        
    }
    NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:[_infoDic[@"row"]integerValue] inSection:0]; //刷新第0段第2行
    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
}
#pragma mark-->heardViewDelegate chooseTimeBtn
- (void)chooseTime:(UIButton *)sender ClickTag:(NSInteger)tag
{
    ChooseTimeBtnTag = tag;
    CJCalendarViewController *calendarController = [[CJCalendarViewController alloc] init];
    calendarController.view.frame = self.view.frame;
    
    calendarController.delegate = self;
    NSArray *arr = [sender.titleLabel.text componentsSeparatedByString:@"-"];
    
    if (arr.count > 1) {
        [calendarController setYear:arr[0] month:arr[1] day:arr[2]];
    }
    
    [self presentViewController:calendarController animated:YES completion:nil];

}
#pragma mark-->CJCalendarViewControllerDelegate
-(void)CalendarViewController:(CJCalendarViewController *)controller didSelectActionYear:(NSString *)year month:(NSString *)month day:(NSString *)day{
    
    if (ChooseTimeBtnTag == 1001) {
        
        if (day.length == 1 && month.length != 1) {
            
            self.heardView.startimeTF.text =  [NSString stringWithFormat:@"%@-%@-0%@", year, month,day];
        }else if (month.length == 1 && day.length != 1){
            self.heardView.startimeTF.text = [NSString stringWithFormat:@"%@-0%@-%@", year, month, day];

        }else if (month.length == 1 && day.length ==1 ){
            self.heardView.startimeTF.text = [NSString stringWithFormat:@"%@-0%@-0%@", year, month, day];

        } else{
            self.heardView.startimeTF.text = [NSString stringWithFormat:@"%@-%@-%@", year, month, day];
        }

        
    }else{
        
        if (day.length == 1 && month.length != 1) {
            
            self.heardView.endtimeTF.text = [NSString stringWithFormat:@"%@-%@-0%@", year, month,day];
            
        }else if (month.length == 1 && day.length != 1){
            self.heardView.endtimeTF.text = [NSString stringWithFormat:@"%@-0%@-%@", year, month, day];

        }else if (month.length == 1 && day.length ==1 ){
            self.heardView.endtimeTF.text = [NSString stringWithFormat:@"%@-0%@-0%@", year, month, day];

        } else{
            self.heardView.endtimeTF.text = [NSString stringWithFormat:@"%@-%@-%@", year, month, day];

        }

    }
    
    
}

#pragma mark-->heardViewDelegate branchCompanyBtn
- (void)chooseTypeOrCompany:(UIButton *)sender ClickTag:(NSInteger)tag
{
    //[self.heardView.searchTF resignFirstResponder];
    if (tag == 1003) {
        
        [self questionTypeNetworking];

    }else if (tag == 1004){
        
        [self FGSload];
    }else{
        
    }
}

/*问题类型接口*/
- (void)questionTypeNetworking{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:QuestionTypeURL parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [_typeIDArray removeAllObjects];
        [_typeNameArray removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        SuggesDataModel *datamodel = [[SuggesDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (SuggesAspectModel *model in datamodel.aspect) {
            
            [_typeNameArray addObject:model.aspectName];
            [_typeIDArray addObject:[NSString stringWithFormat:@"%ld",model.aspectId]];
        }
        MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:nil style:MHSheetStyleDefault itemTitles:_typeNameArray];
        __weak typeof(self) weakSelf = self;
        [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
            weakSelf.heardView.questionTypeTF.text = title;
            sugesTypeId = [_typeIDArray[index]integerValue];
        }];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        //NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        //NSInteger status = responses.statusCode;
       [self showAlert:@"出错了" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
    }];
}
//分公司
- (void)FGSload{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_partFGS parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [_FGS_arry removeAllObjects];
        [_FGSid_arry removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        YYpartDataModel *model = [[YYpartDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (YYbeanListModel *Bmodel in model.beanList) {
            [_FGS_arry addObject:Bmodel.branchName];
            [_FGSid_arry addObject:[NSString stringWithFormat:@"%ld",Bmodel.branchId]];
        }
        MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:nil style:MHSheetStyleDefault itemTitles:_FGS_arry];
        __weak typeof(self) weakSelf = self;
        [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
            weakSelf.heardView.branchCompanyTF.text = title;
            branchId = [_FGSid_arry[index]integerValue];
        }];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self showAlert:@"出错了" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
    }];
}


- (void)HeardViewSearchClick:(UIButton *)sender{
    
    [self.heardView.searchTF resignFirstResponder];
    [_UnusualBsView removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}

- (void)networking:(NSDictionary *)prameter{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:SuggesAndComSearchURL parameters:prameter progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        SugAndComDataModel *datamodel = [[SugAndComDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (SugAndComBeanListModel *listModel in datamodel.beanList) {
            
            [_dataSource addObject:listModel];
        }
        if ([dic[@"status"]integerValue] == 1) {
            
            if (_dataSource.count == 0) {
                
                self.tableview.scrollEnabled = NO;
                _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 161, kSCREEN_WIDTH, kSCREEN_HEIGHT-161) UnusualState:NotingDataStatus AndUnusualTitle:@"没有搜索到您要的数据"];
                _UnusualBsView.delegate = self;
                [self.view addSubview:_UnusualBsView];
            }else{
                
            }
            
        }else{
            self.tableview.scrollEnabled = NO;
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 161, kSCREEN_WIDTH, kSCREEN_HEIGHT-161) UnusualState:ObtainDataFalStatus AndUnusualTitle:@"当前没有数据"];
            _UnusualBsView.delegate = self;
            [self.view addSubview:_UnusualBsView];
        }
                [self.tableview reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self endRefresh];
        self.tableview.scrollEnabled = NO;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500 ) {
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 161, kSCREEN_WIDTH, kSCREEN_HEIGHT-161) UnusualState:ServerQuestionStatus AndUnusualTitle:@"不好...服务器出错"];
            _UnusualBsView.delegate = self;
            [self.view addSubview:_UnusualBsView];
        }else if (status == 404) {
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 161, kSCREEN_WIDTH, kSCREEN_HEIGHT-161) UnusualState:404 AndUnusualTitle:@"不好...访问链接出错"];
            _UnusualBsView.delegate = self;
            [self.view addSubview:_UnusualBsView];
        }else if(status == 0){
            
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 161, kSCREEN_WIDTH, kSCREEN_HEIGHT-161) UnusualState:0 AndUnusualTitle:@"不好...连接超时了"];
            _UnusualBsView.delegate = self;
            [self.view addSubview:_UnusualBsView];
        }else{
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 161, kSCREEN_WIDTH, kSCREEN_HEIGHT-161) UnusualState:OtherStatus AndUnusualTitle:@"其他异常"];
            _UnusualBsView.delegate = self;
            [self.view addSubview:_UnusualBsView];
        }

    }];
}
- (void)RefreshBtnClick:(UIButton *)sender{
    
    self.tableview.scrollEnabled = YES;
    [_UnusualBsView removeFromSuperview];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SuggesOrComplainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = UIColorFromRGB(0xf0f0f0);
    cell.delegate = self;
    SugAndComBeanListModel *model = _dataSource[indexPath.row];
    [cell fillCellWithModel:model WithRow:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.heardView.searchTF resignFirstResponder];
    SugAndComBeanListModel *model = _dataSource[indexPath.row];
    SugAndComDetailVC *detailVC = [[SugAndComDetailVC alloc]init];
    if (model.anonymity  == 0) {
        _WhetherName = model.smtPs;
    }else{
        _WhetherName = @"迭名";
    }
    if (model.supportState == 1) {
        _upImage = @"thumb_up_blue";
    }else{
        _upImage = @"thumb_up";
    }
    detailVC.detailData = @{@"title":model.title,@"content":model.suggestion,@"supimage":_upImage,@"supportN":[NSString stringWithFormat:@"赞同数:%ld",model.supportNum],@"pson":[NSString stringWithFormat:@"提交人:%@",_WhetherName],@"branchCom":model.branchName,@"aspectOn":[NSString stringWithFormat:@"%ld",model.aspectOn],@"time":model.time,@"sugTypeID":[NSString stringWithFormat:@"%ld",model.type]};
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}



@end
